import PopupPicker from "vux/src/components/popup-picker/index.vue";

import playMethods from "./playMethods/playMethods";
import chatRoom from "./chatRoom/chatRoom";
import roomTitle from "./roomTitle/roomTitle";
import askRoad from "./askRoad/askRoad";
import { mapGetters, mapActions } from "vuex";
import { initWebSocket, websocketsend, websock } from "@/assets/js/websocket";
import router from "@/router";
import template from "./roomTemplate";
const { render, staticRenderFns } = template;

export default {
  render,
  staticRenderFns,
  components: {
    PopupPicker,
    playMethods,
    chatRoom,
    roomTitle,
    askRoad,
  },
  mounted() {
    if (!_.isEmpty(this.userInfo)) {
      this.userData = this.userInfo;
      if (_.isEmpty(this.userData.id)) {
        this.userData.id = this.userData.uid;
      }
      this.initRoom();
    }
  },
  created() {},
  data() {
    return {
      lottery_type: this.$route.query.lottery_type,
      roomId: this.$route.query.id,
      roomListData: {},
      roomName1: "",

      allMessage: {}, //websock总数据
      timeMessage: {}, //倒计时
      newLotResult: {}, //开奖结果
      userData: {},
      plTipText: "",
      popupNavShow: false,
      showLotList: false,
      showLotList2: false,
      userMessage: "",

      zjFlag: false,
      zjMoney: 0,
      serTimer: {},
      csTimer: {},
      csCount: 0,
    };
  },
  computed: {
    ...mapGetters([
      "roomData",
      "userInfo",
      "accountData",
      "serTime",
      "lotRstData",
    ]),
  },
  methods: {
    ...mapActions(["SET_USER_INFO_DATA", "SET_ACCOUNT_DATA"]),

    sendMessage: function () {
      if (_.isEmpty(this.userMessage)) {
        this.$vux.toast.text("消息不能为空", "bottom");
        return;
      }
      const agentData = {
        commandid: "3003",
        nickname: this.userData.nickname,
        content: this.userMessage,

        uid: this.userData.uid || this.userData.id,
        avatar: this.userData.avatar,
      };
      websocketsend(agentData);
      this.userMessage = "";
    },
    hidePanel: function (event) {
      var lotRecord = document.getElementById("lotRecord");
      var lotHistory = document.getElementById("lotHistory");
      if (lotRecord) {
        if (!lotRecord.contains(event.target)) {
          this.showLotList = false;
        }
      }
      if (lotHistory) {
        if (!lotHistory.contains(event.target)) {
          this.showLotList2 = false;
        }
      }
    },
    setLotList: function (res) {
      this.showLotList = res;
    },
    setLotList2: function (res) {
      this.showLotList2 = res;
    },
    initRoom: function () {
      if (!_.isEmpty(this.userData)) {
        this.initWebSocket();
      }
      var playMethod = document.getElementById("playMethod");
      var roomTop = document.getElementById("roomTop");
      var chatIptBox = document.getElementById("chatIptBox");
      playMethod.style.height =
        document.documentElement.clientHeight - roomTop.offsetHeight + "px";
      window.onresize = function () {
        setTimeout(function () {
          playMethod.style.height =
            document.documentElement.clientHeight - roomTop.offsetHeight + "px";
        }, 500);
      };
      this.$http
        .post(this.urlRequest + "?m=win&c=lobby&a=getLotteryRoomList", {
          type: this.lottery_type,
        })
        .then((result) => {
          if (result.status == 0) {
            this.roomListData = result.data;
            console.log(result.data)
            console.log('room.js==========')
            this.setRoomTitle();
          }
        });
    },
    initWebSocket() {
      this.$http
        .post(this.urlRequest + "?m=api&c=workerman&a=getAllws", {})
        .then((result) => {
          var that = this;
          var address = [];
          if (!_.isEmpty(result)) {
            var j = 0;
            for (var i in result) {
              console.log(result[i])
              // if(result[i] === 'qjw789.com:7272'){
              //   address[j] = new WebSocket("wss://" + '103.60.221.86:7272');
              // }else{
              //   address[j] = new WebSocket("wss://" + result[i]);
              // }
              address[j] = new WebSocket("ws://" + result[i]);
              // address[j] = new WebSocket("wss://" + result[i]);
              j++;
            }
            for (var i in address) {
              address[i].addEventListener("open", function (event) {
                initWebSocket(event.currentTarget.url);
                that.getData();
                for (var j in address) {
                  address[j].close();
                }
              });
            }
            this.csTimer = setTimeout(() => {
              var flag = true;
              if (websock.readyState == 1) {
                flag = false;
              }
              if (flag) {
                that.$vux.alert.show({
                  content: "连接房间超时，请重试",
                  onHide: () => {
                    that.$router.push({
                      path: "/home",
                    });
                  },
                });
              }
            }, 5000 * j);
          }
        });
    },
    threadPoxi: function () {
      // 心跳连接
      const agentData = { commandid: "3012", uid: this.userData.id };
      websocketsend(agentData);
      var xintiao = setInterval(function () {
        websocketsend(agentData);
      }, 20000);
      websock.addEventListener("close", function (event) {
        clearInterval(xintiao);
      });
    },
    serTimerFun: function (data) {
      clearInterval(this.serTimer);
      var obj = data.serTime;
      this.serTimer = setInterval(() => {
        obj += 1;
        this.$store.commit("setSerTime", obj);
      }, 1000);
    },
    getData: function () {
      var that = this;

      websock.addEventListener("open", function (event) {
        that.$vux.loading.hide();
        that.threadPoxi();
        const agentData1 = {
          commandid: "3002",
          uid: that.userData.id,
          roomid: that.$route.query.id,
        };
        websocketsend(agentData1);
        const agentData2 = {
          commandid: "3017",
          uid: that.userData.id,
          roomid: that.$route.query.id,
          lottery_type: that.$route.query.lottery_type,
        };
        websocketsend(agentData2);
      });
      websock.addEventListener("message", function (event) {
        let data = JSON.parse(event.data);
        if (data.commandid != 3023) {
          console.log(data);
        }
        if (data.commandid == 3004 || data.commandid == 3007) {
          if (
            data.content.slice(1, 3) == "追号" ||
            data.content.slice(0, 4) == "当前不在" ||
            data.content.slice(0, 4) == "投注失败"
          ) {
            that.$vux.alert.show({
              content: data.content,
            });
          }

          if (that.userData.id == data.uid && data.commandid == 3007) {
            that.$vux.toast.show({
              text: "投注成功",
            });
          }
          if (data.commandid == 3004 && data.has_not_money == 1) {
          }
        } else if (data.commandid == 3005) {
        } else if (data.commandid == 3001) {
          var obj = that.roomData;
          obj.serTime = data.serTime;
          obj.issue = data.issue;
          that.timeMessage = data; // loading原因
          if (
            that.lottery_type == 4 ||
            that.lottery_type == 9 ||
            that.lottery_type == 14
          ) {
            that.timeMessage.issue = that.timeMessage.issue.substr(4);
          }
          that.$store.commit("setRoomData", obj);
          that.serTimerFun(data);
        } else if (data.commandid == 3014) {
        } else if (data.commandid == 3011) {
          that.newLotResult = data;
        } else if (data.commandid == 3015) {
        } else if (data.err) {
        } else if (data.commandid == 3019) {
        } else if (data.commandid == 3022) {
        } else if (data.commandid == 3018) {
        } else if (data.commandid == 3023) {
        } else if (data.commandid == 3010) {
          var accountData = that.accountData;
          accountData.money_usable = data.money;
          that.SET_ACCOUNT_DATA({
            Obj: accountData,
          });
        } else if (data.commandid == 3026) {
          var accountData = that.accountData;
          accountData.money_usable = data.use_money;
          that.SET_ACCOUNT_DATA({
            Obj: accountData,
          });
          that.zjMoney = data.money;
          that.zjFlag = true;
        } else if (data.commandid == 3025) {
        } else if (data.commandid == 3888) {
          if (!_.isEmpty(data.greet)) {
            that.$vux.alert.show({
              title: "温馨提示",
              content: "<pre>" + data.greet + "</pre>",
            });
          }
        }
        if (data.commandid != 3023) {
          that.allMessage = data;
          // console.log('------')
          // console.log(data.commandid)
          // console.log(data)
          // console.log('------')
        }
      });
      websock.addEventListener("close", function (event) {
        if (event.code == 1006) {
        }
        console.log(event, "room.js closeeeeeeeeeeeeeeeeee");
        websock.close();
      });
      websock.addEventListener("error", function (event) {
        if (event.type == "error") {
          initWebSocket();
        }
        console.log(event, "error");
      });
    },
    setRoomTitle: function () {
      for (var i = 0; i < this.roomListData.p_room.length; i++) {
        if (
          this.roomId == this.roomListData.p_room[i].id ||
          this.roomId == this.roomListData.p_room[i].idd
        ) {
          this.roomName1 = this.roomListData.p_room[i].title;
          this.plTipText = this.roomListData.p_room[i].odds_exp;
          var obj = this.roomData;
          obj.minBetMoney = this.roomListData.p_room[i].lower;
          this.$store.commit("setRoomData", obj);
        }
      }
    },
    showPlayMethods: function (flag) {
      var obj = this.roomData;
      obj.showPmDlg = true;
      obj.plTipText = this.plTipText;
      obj.notZhuiHao = flag;
      console.log('room.js---',obj)
      this.$store.commit("setRoomData", obj);
    },
    playMethodsMaskClick: function () {
      this.roomData.showPmDlg = false;
    },
  },
  watch: {
    lotRstData: {
      handler(newVal, oldVal) {
        if (!newVal.loadingFailed) {
          this.allMessage = JSON.parse(JSON.stringify(newVal));
        }
      },
    },
    userInfo: {
      handler(newVal, oldVal) {
        if (_.isEmpty(newVal)) {
          this.$vux.toast.text("登录失效，请重新登录", "bottom");
          return;
        }
        this.userData = newVal;
        if (_.isEmpty(this.userData.id)) {
          this.userData.id = this.userData.uid;
        }
      },
      deep: true,
    },
  },
  beforeDestroy() {
    websock.close();
    clearInterval(this.serTimer);
    clearInterval(this.csTimer);
  },
  deactivated() {
    websock.close();
  },
};

// WEBPACK FOOTER //
// ./src/components/room/room.vue
